<template>
  <div class="edit_article">
    <el-card>
      <el-form ref="form" :model="form" label-position="right" label-width="100px" :rules="rules">
        <el-form-item label="文章名称" prop="name">
          <el-input style="width: 200px;" size="small" v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="封面图" prop="cover">
          <el-upload
            v-model="form.cover"
            ref="cover"
            class="avatar-uploader"
            :action="baseUrl+'upload/resource'"
            :headers="{Authorization: token}"
            :show-file-list="false"
            :before-upload="beforeUpload"
            :on-success="handleAvatarSuccess"
            accept="image/png, image/jpeg, image/gif"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input v-model="form.desc" style="width: 300px;" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="点击时长" prop="listenTime">
          <el-input-number size="small" v-model="form.listenTime"></el-input-number>
        </el-form-item>
        <el-form-item label="文章内容" prop="content">
          <!-- <TinyMce v-if="showTinymce" v-model="form.content"></TinyMce> -->
          <ue :defaultMsg="form.content" :id="'ue'" ref="ue" />
        </el-form-item>
      </el-form>
      <el-row>
        <el-button class="f-r" type="primary" @click="subServie('form')">保存</el-button>
        <el-button class="f-r m-r-10">取消</el-button>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import { createArticle, upladeArticle ,getArticleDetail} from "@/api/article";
// import TinyMce from '@/components/Tinymce'
import ue from "@/components/Ueditor";
export default {
  name: "",
  components: { ue},
  data() {
    var checkContent = (rule, value, callback) => {
      let content = this.$refs.ue.getUEContent();
      if (!content) {
        return callback(new Error("请输入文章内容"));
      }else {
        this.form.content = content
        callback();
      }
    };
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      form: {
        name: "",
        cover: "",
        content: "",
        listenTime: 2,
        desc: ''
      },
      imageUrl: "",
      showTinymce: false,
      token: "Bearer " + localStorage.getItem("Token"),
      rules: {
        name: [{ required: true, message: "请输入文章名称", trigger: "blur" }],
        cover: [{ required: true, message: "请上传封面图", trigger: "change" }],
        content: [{required: true, validator: checkContent, trigger: "blur" }],
        desc: [{required: true, message: "请输入描述", trigger: "blur" }],
      }
    };
  },
  created() {
    if (this.$route.query.id) {
      this.queryData(); // 列表数据回显
    } else {
      this.showTinymce = true;
    }
  },
  methods: {
    queryData() {
        getArticleDetail({id: this.$route.query.id}).then(res => {
            console.log(res);
            const data = res.data
            this.form = {
                name: data.name,
                cover: data.cover_url,
                content: data.content,
                desc: data.desc,
                listenTime: data.listenTime
            }
            this.$refs.ue.setUEContent(data.content)
            this.imageUrl = data.cover_url
            this.showTinymce = true;
        });
    },
    beforeUpload(file) {
      console.log(file)
      let fileSize = 128*1024,
          errorMsg = '您上传的资源过大，请上传128kb以内的图片哦！',
          fileSuffix = file.name.substring(file.name.lastIndexOf('.')+1)
          if(fileSuffix != 'png'&&fileSuffix != 'jpeg'&&fileSuffix != 'jpg'){
              this.$message.error('请上传png、jpeg的图片资源');
              return
          }
          if(file.size>fileSize){
              this.$message.error(errorMsg);
              return false
          }
    },
    handleAvatarSuccess(res, file) {
      console.log(res);
      this.form.cover = res.data.imageUrl;
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    subServie(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let param = {
            ...this.form
          };
          if (this.$route.query.id) {
            param.id = this.$route.query.id;
            upladeArticle(param).then(res => {
              console.log(res);
               this.$message({
                message: '恭喜你，创建成功',
                type: 'success'
            });
              this.$router.replace({ name: "articleList"});
            });
          } else {
            createArticle(param).then(res => {
                this.$message({
                message: '恭喜你，编辑成功',
                type: 'success'
            });
              this.$router.replace({ name: "articleList"});
              console.log(res);
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    }
  }
};
</script>
<style lang='scss'>
.edit_article {
  .el-form-item__label {
    font-size: 12px;
  }
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}
.avatar {
  width: 150px;
  height: 150px;
  display: block;
}
</style>